<?php

namespace app\admin\model;

use app\admin\model\factor\CarbonFactor;
use app\admin\model\template\Template;
use think\Db;
use think\Model;

class Node extends Model
{

    // 表名
    protected $name = 'node';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    public function getFactorNameAttr()
    {
        return $this->factorInfo()->value('name') ?: '';
    }

    public function factorInfo()
    {
        return $this->hasOne(CarbonFactor::class, 'id', 'factor_id')->setEagerlyType(0);
    }


    // 获取所有父级ID

    public function getParentIdsAttr($value, $data)
    {
        return array_filter(explode('-', trim($data['path'], '-')));
    }

    // 获取所有子级ID
    public function getChildrenIdsAttr($value, $data)
    {
        return self::where('path', 'like', $data['path'] . $data['id'] . '-%')->column('id');
    }

    // 获取所有产品子级ID
    public function getProductChildrenIdsAttr($value, $data)
    {
        return self::where('path', 'like', $data['path'] . $data['id'] . '-%')->where('is_factor', 0)->column('id');
    }

    // 获取所有引用因子库子级ID
    public function getFactorChildrenIdsAttr($value, $data)
    {
        return self::where('path', 'like', $data['path'] . $data['id'] . '-%')->where('is_factor', 1)->column('id');
    }

    // 获取因子
    public function getFactorAttr($value, $data)
    {
        return Db::name('carbon_factor')->where('id', $data['factor_id'])->value('carbon_factor_result_kg');
    }

    // 获取因子编号
    public function getFactorSnAttr($value, $data)
    {
        return Db::name('carbon_factor')->where('id', $data['factor_id'])->value('sn');
    }

    // 获取因子所属人
    public function getFactorUserAttr($value, $data)
    {
        return Db::name('carbon_factor')->where('id', $data['factor_id'])->value('user_id');
    }

    public function product()
    {
        return $this->belongsTo('Product');
    }

    public function getProduceQualityAttr($value, $data)
    {
        if (empty($value)) return $value;
        return rtrim(rtrim($value, '0'), '.');
    }

    public function getFactorQuotesAttr($value, $data)
    {
        if (empty($value)) return $value;
        return rtrim(rtrim($value, '0'), '.');
    }

    public function factor()
    {
        return $this->hasOne(CarbonFactor::class, 'id', 'factor_id');
    }

    public function template()
    {
        return $this->hasOne(Template::class, 'id', 'from_template');
    }
}
